import traceback
import sys
import os
import logging
from views.main_window import MainWindow

def setup_logging():
    """配置日志记录器"""
    log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'app_debug.log')
    logging.basicConfig(
        filename=log_file,
        level=logging.DEBUG,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )

def handle_exception(exc_type, exc_value, exc_traceback):
    """处理未捕获的异常"""
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    
    error_msg = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
    logging.critical(f"未捕获的异常: {error_msg}")
    
    # 尝试显示错误信息框（仅当 Tkinter 可用时）
    try:
        import tkinter as tk
        from tkinter import messagebox
        root = tk.Tk()
        root.withdraw()
        messagebox.showerror(
            "致命错误", 
            f"程序遇到致命错误:\n\n{error_msg}\n\n详细信息已记录到: {os.path.abspath('app_debug.log')}"
        )
    except:
        print(f"致命错误: {error_msg}")
        input("按Enter键退出...")


if __name__ == "__main__":
    # 设置全局异常处理器
    sys.excepthook = handle_exception
    
    # 配置日志
    setup_logging()
    
    # 确保资源路径正确
    try:
        logging.info("程序启动")
        
        # 初始化应用
        app = MainWindow()
        logging.info("主窗口创建成功")
        
        # 处理资源路径问题（重要！）
        if hasattr(sys, '_MEIPASS'):
            # PyInstaller 打包模式
            base_path = sys._MEIPASS
        else:
            # 开发模式
            base_path = os.path.dirname(os.path.abspath(__file__))
            
        # 如果 MainWindow 有接受资源路径的方法
        if hasattr(app, 'set_base_path'):
            app.set_base_path(base_path)
            logging.info(f"设置资源路径: {base_path}")
        
        # 运行主循环
        app.mainloop()
        logging.info("程序正常退出")
    except KeyboardInterrupt:
        logging.info("用户中断程序")
        app.quit_application()
    except Exception as e:
        logging.exception("程序初始化失败")
        # 确保错误被正确报告
        handle_exception(type(e), e, e.__traceback__)